package com.demo.supplier;

import com.demo.supplier.dto.LoginDto;
import com.demo.supplier.entity.LoginLog;
import com.demo.supplier.entity.OperationLog;
import com.demo.supplier.mapper.LoginLogRepository;
import com.demo.supplier.mapper.OperationLogRepository;
import com.demo.supplier.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.ActiveProfiles;

import java.util.List;

/**
 * 登录日志AOP+MQ功能测试
 * 
 * @author demo
 */
@Slf4j
@SpringBootTest
@ActiveProfiles("test")
public class LoggingTest {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private LoginLogRepository loginLogRepository;

    @Autowired
    private OperationLogRepository operationLogRepository;

    @Test
    public void testLoginFailureLoggingWithMQ() {
        log.info("开始测试登录失败日志记录（AOP+MQ）");
        
        // 测试用户名不存在的登录失败
        LoginDto loginDto = new LoginDto();
        loginDto.setUsername("nonexistent_user");
        loginDto.setPassword("wrong_password");
        
        try {
            sysUserService.login(loginDto);
        } catch (Exception e) {
            log.info("登录失败异常: {}", e.getMessage());
        }
        
        // 等待RabbitMQ消息处理
        try {
            Thread.sleep(5000); // MQ处理需要更长时间
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        // 查询最新的登录日志
        List<LoginLog> loginLogs = loginLogRepository.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
        
        log.info("最新登录日志数量: {}", loginLogs.size());
        if (!loginLogs.isEmpty()) {
            LoginLog latestLog = loginLogs.get(0);
            log.info("最新登录日志: 用户名={}, 结果={}, 失败原因={}, IP={}", 
                    latestLog.getUsername(), 
                    latestLog.getLoginResult(), 
                    latestLog.getFailureReason(),
                    latestLog.getIp());
        }
    }
    
    @Test
    public void testOperationLogging() {
        log.info("开始测试操作日志记录");
        
        // 查询最新的操作日志
        List<OperationLog> operationLogs = operationLogRepository.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
        
        log.info("最新操作日志数量: {}", operationLogs.size());
        if (!operationLogs.isEmpty()) {
            OperationLog latestLog = operationLogs.get(0);
            log.info("最新操作日志: 用户名={}, 操作={}, 模块={}, 描述={}, 响应={}", 
                    latestLog.getUsername(), 
                    latestLog.getOperation(), 
                    latestLog.getModule(),
                    latestLog.getDescription(),
                    latestLog.getResponseData());
        }
    }
}